package com.frame.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import com.jfinal.plugin.activerecord.dialect.Dialect;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;

/**
 * @author LRC
 * @createDate 2015年5月19日
 * @description 数据源配置文件单例对象
 */
public class DataSourceConfig {
	
	private Properties pr;
	private static DataSourceConfig config = new DataSourceConfig();
	private String fileName = "DataSource.properties";
	private List<Params> ps = new ArrayList<Params>();
	/**
	 * 配置属性
	 * @author LRC
	 *
	 */
	public class Params{
		public String name;
		public boolean master;//是否主数据源
		public Dialect dialect;
		public boolean enable;
		public String driver;
		public String url;
		public String username;
		public String password;
		@Override
		public String toString() {
			return name+":"+dialect+":"+driver+":"+url+":"+username+":"+password;
		}
	}
	
	/**
	 * 构造器说明：加载配置文件
	 */
	private DataSourceConfig(){
		try{
			pr = new Properties();
			pr.load(DataSourceConfig.class.getClassLoader().getResourceAsStream(fileName));
			this.init();
		}catch(Exception e){
			throw new RuntimeException("加载数据源配置文件错误",e);
		}
	}
	
	public static DataSourceConfig getInstance(){
		return config;
	}
	private Dialect getDialect(String type){
		if("ORACLE".equals(type.toUpperCase())){
			return new OracleDialect();
		}
		if("MYSQL".equals(type.toUpperCase())){
			return new MysqlDialect();
		}
		return null;
	}
	/**
	 * 初始化，获取数据源参数
	 */
	private void init(){
		//获取数据源名
		String end = ".dialect";
		Set<Object> keys = this.pr.keySet();
		for(Object k : keys){
			String key = k.toString();
			if(key.endsWith(end)){
				String name = key.substring(0,key.indexOf(end));
				Boolean enable = Boolean.parseBoolean(this.pr.getProperty(name+".enable"));
				if(enable==null||!enable)continue;
				Params c = new Params();
				c.name = name;
				c.master = Boolean.parseBoolean(this.pr.getProperty(name+".master"));
				String dialectType= this.pr.getProperty(name+".dialect");
				c.dialect = this.getDialect(dialectType);
				c.enable = enable;
				c.driver = this.pr.getProperty(name+".driver");
				c.url = this.pr.getProperty(name+".url");
				c.username = this.pr.getProperty(name+".username");
				c.password = this.pr.getProperty(name+".password");
				this.ps.add(c);
			}
		}
	}
	public List<Params> getPs() {
		return ps;
	}

	public void setPs(List<Params> ps) {
		this.ps = ps;
	}

	/**
	 * 应用版本:v1.0
	 * 功能说明：根据给定的key查找配置文件中对应的value
	 * @param key
	 * @return
	 */
	public String getValue(String key){
		if(key==null)
			return null;
		String value = pr.getProperty(key);
		return value;
	}
	
}
